package com.qf.day3;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @date 2022/3/26
 * @desc   转发
 *
 *  转发是指 一个web 资源收到客户端请求  让服务器去调用另一个web资源处理  经常用来做页面跳转
 *
 */
@WebServlet("/request3")
public class Request3Demo extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //test1(req, resp);  // 演示转发

        test2(req, resp);  // req 作为域对象来使用



    }


    private void test2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 省略查询数据库的步骤
        //假设登陆成功   要跳转到 主页面   此时 就可以使用转发

        //在转发之前  往 request 域对象里面 放点东西   带到转发目标

        req.setAttribute("currentUser",username);  // 把数据存入域对象

        //得到转发对象
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/day3/main.jsp");

        requestDispatcher.forward(req, resp);  // 转发 把当前的 req 和 resp 对象带到转发的资源上
    }


    private void test1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 省略查询数据库的步骤

        //假设登陆成功   要跳转到 主页面   此时 就可以使用转发
        //得到转发对象
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/day3/main.jsp");

        requestDispatcher.forward(req, resp);  // 转发 把当前的 req 和 resp 对象带到转发的资源上
    }
}
